/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demo.controller;

import demo.model.util.Constant;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @author Admin
 */
public abstract class WebController extends WebInit {

    private ArrayList<String> errors;
    private ArrayList<String> messages;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(Constant.RESPONSE_ENCODING);
        request.setCharacterEncoding(Constant.REQUEST_ENCODING);
        this.errors = new ArrayList();
        this.messages =new ArrayList<String>();
        try {
            this.init(request, response);
            if (isAuthorize(request, response)) {           
                String actionType = request.getParameter("ACTION") != null ? request.getParameter("ACTION")  : Constant.DEFAULT_ACTION  ;
                if(actionType!=null){
                    Object obj = this; 
                    Method method = this.getClass().getMethod(actionType,HttpServletRequest.class,HttpServletResponse.class); 
                    method.invoke(obj, request,response);
                    
                }else{
//                    redirect("/home/display",response);
                }
                
            } else {
                //Redirect login
//                redirect("/login/showLogIn", response);
            }

        } catch (Exception ex) {
            redirect("/error/display", response);
            ex.printStackTrace(System.out);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void addError(String msg) {
        this.errors.add(msg);
    }
    protected void addMessage(String msg) {
        this.messages.add(msg);
    }

    @Override
    protected void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("PAGE_LINK", request.getServletPath());
        request.setAttribute("ERROR", errors);
        request.setAttribute("MESSAGE", messages);
        super.forward(path, request, response);
    }


}
